#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qdebug.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    AvailabeFlag = 0;
    const auto infos = QSerialPortInfo::availablePorts();//find avaliable ports auotmatically
    for (const QSerialPortInfo &info : infos)
    {
        AvailabeFlag = 1;
        ui->serialName->addItem(info.portName());
    }
    if(AvailabeFlag != 1)
    {
        ui->serialName->addItem("I LOVE YOU");
    }
}

MainWindow::~MainWindow()
{
    timer->stop();
    qDebug()<<"timer has been shuted down";
    serial.clear();
    serial.close();
    delete ui;
}

void MainWindow::on_openserial_clicked()
{
    serialname = ui->serialName->currentText();
    switch (ui->Baudrate->currentText().toInt()) {
    case 1200:
        baudrate = QSerialPort::Baud1200;
        break;
    case 2400:
        baudrate = QSerialPort::Baud2400;
        break;
    case 9600:
        baudrate = QSerialPort::Baud9600;
        break;
    case 115200:
        baudrate = QSerialPort::Baud115200;
        break;
    case 38400:
        baudrate = QSerialPort::Baud38400;
        break;
    default:
        break;
    }

    switch (ui->Bits->currentText().toInt()) {
    case 5:
        serial.setDataBits(QSerialPort::Data5);
        break;
    case 6:
        serial.setDataBits(QSerialPort::Data6);
        break;
    case 7:
        serial.setDataBits(QSerialPort::Data7);
        break;
    case 8:
        serial.setDataBits(QSerialPort::Data8);
        break;
    default:
        break;
    }

    switch (ui->Patiry->currentIndex()) {
    case 0:
        serial.setParity(QSerialPort::OddParity);
        break;
    case 1:
        serial.setParity(QSerialPort::EvenParity);
        break;
    default:
        serial.setParity(QSerialPort::NoParity);
        break;
    }

    switch(ui->Stop->currentIndex())
    {
        case 0:
            serial.setStopBits(QSerialPort::OneStop);
        break;
        case 1:
            serial.setStopBits(QSerialPort::OneAndHalfStop);
        break;
        case 2:
            serial.setStopBits(QSerialPort::TwoStop);
        break;
        default:
            serial.setStopBits(QSerialPort::OneStop);
        break;
    }

    serial.setBaudRate(baudrate);
    serial.setPortName(serialname);
    //serial.setReadBufferSize(8);
    serial.open(QSerialPort::ReadWrite);

}

void MainWindow::receiver()
{
    receivedata = serial.readAll();

    if(receivedata != NULL)
    {
        qDebug()<<receivedata<<"|";
        if(ui->Receivehex->isChecked())
            ui->received->append(receivedata.toHex());
        else {
            ui->received->append(receivedata);
        }
    }
    serial.clear();
}

void MainWindow::on_closebutton_clicked()
{
    timer->stop();
    qDebug()<<"timer has been shuted down";
    serial.clear();
    serial.close();
}


void MainWindow::on_senddata_button_clicked()
{
    senddata = ui->senddata->toPlainText().toLatin1().data();
    qDebug()<<senddata;
    if(ui->Sendhex->isChecked())
        serial.write(senddata.toHex());
    else
        serial.write(senddata);
    if(serial.error()!=QSerialPort::NoError)
        qDebug()<<serial.error();

}

void MainWindow::on_START_clicked()
{
    on_openserial_clicked();
    senddata[0] = 0xff;
    senddata[1] = 0xff;
    senddata[2] = 0xff;
    serial.write(senddata.toHex());
}
void MainWindow::on_start_receive_clicked()
{
    if(serial.error()==QSerialPort::NoError)
    {
        timer->start(10);
        qDebug()<<"timer has inited";
        QObject::connect(timer,SIGNAL(timeout()),this,SLOT(receiver()));
    }
    else
        qDebug()<<serial.error();
}

void MainWindow::on_STOP_clicked()
{
    on_openserial_clicked();
    senddata[0] = 230;
    senddata[1] = 230;
    senddata[2] = 230;
    serial.write(senddata.toHex());
}
void MainWindow::on_stop_receive_clicked()
{
    timer->stop();
    distime->stop();
    qDebug()<<"timer has been shuted down";
}
void MainWindow::on_black_line_button_clicked()
{
    bool hextodec;
    int Datay=0;

    rubberBand = new QRubberBand(QRubberBand::Rectangle, ui->black_line);
    /*
    on_openserial_clicked();
    QByteArray temp = serial.read(8);
    QByteArray temp1;

    if(!temp.isEmpty())
    {
        if(temp.toHex()[0] == 'd' && temp.toHex()[1]=='a' && temp.toHex()[14]=='d' &&temp.toHex()[15]=='c')
        {
            temp1.append(temp.toHex()[8]).append(temp.toHex()[9]);
            qDebug()<<"0";
        }
        else if(temp.toHex()[1] == 'd' && temp.toHex()[2]=='a' && temp.toHex()[15]=='d' &&temp.toHex()[0]=='c')
        {
            temp1.append(temp.toHex()[11]).append(temp.toHex()[12]);
            qDebug()<<"1";
        }
        else if(temp.toHex()[2] == 'd' && temp.toHex()[3]=='a' && temp.toHex()[0]=='d' &&temp.toHex()[1]=='c')
        {
            temp1.append(temp.toHex()[12]).append(temp.toHex()[13]);
            qDebug()<<"2";
        }
        else if(temp.toHex()[3] == 'd' && temp.toHex()[4]=='a' && temp.toHex()[1]=='d' &&temp.toHex()[2]=='c')
        {
            temp1.append(temp.toHex()[13]).append(temp.toHex()[14]);
            qDebug()<<"3";
        }
        else if(temp.toHex()[4] == 'd' && temp.toHex()[5]=='a' && temp.toHex()[2]=='d' &&temp.toHex()[3]=='c')
        {
            temp1.append(temp.toHex()[14]).append(temp.toHex()[15]);
            qDebug()<<"4";
        }
        else if(temp.toHex()[5] == 'd' && temp.toHex()[6]=='a' && temp.toHex()[3]=='d' &&temp.toHex()[4]=='c')
        {
            temp1.append(temp.toHex()[15]).append(temp.toHex()[0]);
            qDebug()<<"5";
        }
        else if(temp.toHex()[6] == 'd' && temp.toHex()[7]=='a' && temp.toHex()[4]=='d' &&temp.toHex()[5]=='c')
        {
            temp1.append(temp.toHex()[0]).append(temp.toHex()[1]);
            qDebug()<<"6";
        }
        else if(temp.toHex()[7] == 'd' && temp.toHex()[8]=='a' && temp.toHex()[5]=='d' &&temp.toHex()[6]=='c')
        {
            temp1.append(temp.toHex()[1]).append(temp.toHex()[2]);
            qDebug()<<"7";
        }
        else if(temp.toHex()[8] == 'd' && temp.toHex()[9]=='a' && temp.toHex()[6]=='d' &&temp.toHex()[7]=='c')
        {
            temp1.append(temp.toHex()[2]).append(temp.toHex()[3]);
            qDebug()<<"8";
        }
        else if(temp.toHex()[9] == 'd' && temp.toHex()[10]=='a' && temp.toHex()[7]=='d' &&temp.toHex()[8]=='c')
        {
            temp1.append(temp.toHex()[3]).append(temp.toHex()[4]);
        }
        else if(temp.toHex()[10] == 'd' && temp.toHex()[11]=='a' && temp.toHex()[8]=='d' &&temp.toHex()[9]=='c')
        {
            temp1.append(temp.toHex()[4]).append(temp.toHex()[5]);
        }
        else if(temp.toHex()[11] == 'd' && temp.toHex()[12]=='a' && temp.toHex()[9]=='d' &&temp.toHex()[10]=='c')
        {
            temp1.append(temp.toHex()[5]).append(temp.toHex()[6]);
        }
        else if(temp.toHex()[12] == 'd' && temp.toHex()[13]=='a' && temp.toHex()[10]=='d' &&temp.toHex()[11]=='c')
        {
            temp1.append(temp.toHex()[6]).append(temp.toHex()[7]);
        }
        else if(temp.toHex()[13] == 'd' && temp.toHex()[14]=='a' && temp.toHex()[11]=='d' &&temp.toHex()[12]=='c')
        {
            temp1.append(temp.toHex()[7]).append(temp.toHex()[8]);
        }
        else if(temp.toHex()[14] == 'd' && temp.toHex()[15]=='a' && temp.toHex()[12]=='d' &&temp.toHex()[13]=='c')
        {
            temp1.append(temp.toHex()[8]).append(temp.toHex()[9]);
        }
        else if(temp.toHex()[15] == 'd' && temp.toHex()[0]=='a' && temp.toHex()[13]=='d' &&temp.toHex()[14]=='c')
        {
            temp1.append(temp.toHex()[9]).append(temp.toHex()[10]);
        }


        distancedata.append(temp1);
        ui->distance_text->append(distancedata);

        qDebug()<<temp1<<"|"<<temp1.toInt(&hextodec,16)<<temp;
        if(AvailabeFlag != 2)
        {
            AvailabeFlag = 2;
            distime->start(10);
            connect(distime,SIGNAL(timeout()),this,SLOT(on_black_line_button_clicked()));
            qDebug("distace timer is actived");
            black_x = 0;
        }
    }
    */
    if(AvailabeFlag != 2)
    {
        AvailabeFlag = 2;
        distime->start(10);
        connect(distime,SIGNAL(timeout()),this,SLOT(on_black_line_button_clicked()));
        connect(ui->black_line, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(mousePress(QMouseEvent*)));
        connect(ui->black_line, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMove(QMouseEvent*)));
        connect(ui->black_line, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseRelease(QMouseEvent*)));
        connect(ui->black_line->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->black_line->xAxis2, SLOT(setRange(QCPRange)));
        connect(ui->black_line->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->black_line->yAxis2, SLOT(setRange(QCPRange)));
        connect(ui->reset_black, SIGNAL(clicked()), this, SLOT(on_reset_black_clicked()));

        qDebug("distace timer is actived");
        black_x = 0;
        ui->black_line->addGraph();
        ui->black_line->graph(0)->addData(black_x,150);//temp1.toInt(&hextodec,16)
        ui->black_line->xAxis->setRange(0,100);
    }
    Datay = 150;
    if(black_x > 100)
    {
       ui->black_line->xAxis->setRange(black_x-50,black_x+150);                //x change with incresing
    }
    if(Datay > 5)
    {
        ui->black_line->yAxis->setRange(Datay-5,Datay+90);                //x change with incresing
    }
    ui->black_line->graph(0)->addData(black_x,Datay);//temp1.toInt(&hextodec,16)
    ui->black_line->replot();
    black_x = black_x + 0.1;

}

void MainWindow::on_stop_biack_line_clicked()
{
    distime->stop();
    AvailabeFlag = 1;
}

void MainWindow::on_Read_Para_clicked()
{
    QByteArray temp;
    temp.append("1").append("2");
    qDebug()<<temp;
}

void MainWindow::on_rangex_textChanged()
{
    ui->black_line->xAxis->setRange(0,ui->rangex->text().toInt());
    ui->black_line->replot();
}

void MainWindow::on_rangey_textChanged()
{
    ui->black_line->yAxis->setRange(0,ui->rangey->text().toInt());
    ui->black_line->replot();
}

//鼠标按下槽函数
void MainWindow::mousePress(QMouseEvent* mevent)
{
    if(mevent->button() == Qt::RightButton)
    {
        qDebug()<<"mousePress";
        rubberOrigin = mevent->pos();
        rubberBand->setGeometry(QRect(rubberOrigin, QSize()));
        rubberBand->show();
    }
}

//鼠标移动槽函数
void MainWindow::mouseMove(QMouseEvent *mevent)
{
    qDebug()<<"mouseMove";
    if(rubberBand->isVisible())
        rubberBand->setGeometry(QRect(rubberOrigin, mevent->pos()).normalized());
}

//鼠标释放槽函数
void MainWindow::mouseRelease(QMouseEvent *mevent)
{
    qDebug()<<"mouseRelease";
    Q_UNUSED(mevent);
    if (rubberBand->isVisible())
    {
        const QRect zoomRect = rubberBand->geometry();
        int xp1, yp1, xp2, yp2;
        zoomRect.getCoords(&xp1, &yp1, &xp2, &yp2);
        double x1 = ui->black_line->xAxis->pixelToCoord(xp1);
        double x2 = ui->black_line->xAxis->pixelToCoord(xp2);
        double y1 = ui->black_line->yAxis->pixelToCoord(yp1);
        double y2 = ui->black_line->yAxis->pixelToCoord(yp2);

        ui->black_line->xAxis->setRange(x1, x2);
        ui->black_line->yAxis->setRange(y1, y2);

        rubberBand->hide();
        ui->black_line->replot();
    }
}

void MainWindow::on_reset_black_clicked()
{
    ui->black_line->rescaleAxes();
    ui->black_line->replot();
}

void MainWindow::on_left_encoder_start_clicked()
{
    ui->left_encode->addGraph();
    ui->left_encode->graph(0)->addData(2,5);
    ui->left_encode->graph(0)->addData(4,1);
    ui->left_encode->replot();
}

void MainWindow::on_start_comm_clicked()
{
    on_openserial_clicked();
    QByteArray temp = serial.read(8);

    if(!temp.isEmpty())
    {
        for(int i=0;i<N;i++)                                    //the buffer of receive
        {
            int j = (i+1)>N?0:(i+1);
            if(temp.toHex()[i] == 'd' && temp.toHex()[j]=='a' && temp.toHex()[i>=2?(i-2):(N-2+i)]=='d' &&temp.toHex()[i>=1?(i-1):(N-i+1)]=='c')
            {
                //fill into buffer it is sastifired

                for(int k = 0;k<N-4;k++)                                //n-4ci
                {
                    if(j<N)
                    {
                        j++;
                    }
                    else
                    {
                        j=0;
                    }
                    SortedDate.append(j);
                }
            }
        }
    }

}
